import { defineStore } from 'pinia'
import { asyncRouterMap, constantRouterMap } from '@/router'
import { flatMultiLevelRoutes } from '@/utils/routerHelper'
import { store } from '../index'
import { cloneDeep } from 'lodash-es'

export interface PermissionState {
  routers: AppRouteRecordRaw[]
  addRouters: AppRouteRecordRaw[]
  isAddRouters: boolean
  menuTabRouters: AppRouteRecordRaw[]
}

export const usePermissionStore = defineStore('permission', {
  state: (): PermissionState => ({
    routers: [],
    addRouters: [],
    isAddRouters: false,
    menuTabRouters: []
  }),
  getters: {
    getRouters(): AppRouteRecordRaw[] {
      return this.routers
    },
    getAddRouters(): AppRouteRecordRaw[] {
      try {
        console.log('getAddRouters被调用，this.addRouters:', this.addRouters)
        if (!this.addRouters || !Array.isArray(this.addRouters)) {
          console.warn('addRouters不是数组或为空，返回空数组')
          return []
        }
        const routes = flatMultiLevelRoutes(cloneDeep(this.addRouters))
        console.log('flatMultiLevelRoutes结果:', routes)
        return routes || []
      } catch (error) {
        console.error('getAddRouters出错:', error)
        return []
      }
    },
    getIsAddRouters(): boolean {
      return this.isAddRouters
    },
    getMenuTabRouters(): AppRouteRecordRaw[] {
      return this.menuTabRouters
    }
  },
  actions: {
    generateRoutes(): Promise<unknown> {
      return new Promise<void>((resolve) => {
        // 直接使用静态路由
        const routerMap = cloneDeep(asyncRouterMap)
        console.log('静态路由生成结果:', routerMap)

        // 动态路由，404一定要放到最后面
        this.addRouters = routerMap.concat([
          {
            path: '/:path(.*)*',
            redirect: '/404',
            name: '404Page',
            meta: {
              hidden: true,
              breadcrumb: false
            },
            children: []
          }
        ])

        console.log('最终addRouters:', this.addRouters)

        // 渲染菜单的所有路由
        this.routers = cloneDeep(constantRouterMap).concat(routerMap)
        console.log('最终routers:', this.routers)

        resolve()
      })
    },

    // 验证路由对象结构的辅助方法
    validateRouteStructure(routes: AppRouteRecordRaw[]): AppRouteRecordRaw[] {
      const validatedRoutes: AppRouteRecordRaw[] = []

      for (const route of routes) {
        if (route && typeof route === 'object') {
          // 确保必要的属性存在
          const validatedRoute: AppRouteRecordRaw = {
            path: route.path || '/',
            name: route.name || '',
            meta: route.meta || {},
            children: []
          }

          // 复制其他属性
          if (route.component) validatedRoute.component = route.component
          if (route.redirect) validatedRoute.redirect = route.redirect

          // 递归验证子路由
          if (route.children && Array.isArray(route.children)) {
            validatedRoute.children = this.validateRouteStructure(route.children)
          }

          validatedRoutes.push(validatedRoute)
        }
      }

      return validatedRoutes
    },
    setIsAddRouters(state: boolean): void {
      this.isAddRouters = state
    },
    setMenuTabRouters(routers: AppRouteRecordRaw[]): void {
      this.menuTabRouters = routers
    }
  },
  persist: [
    {
      pick: ['routers'],
      storage: localStorage
    },
    {
      pick: ['addRouters'],
      storage: localStorage
    },
    {
      pick: ['menuTabRouters'],
      storage: localStorage
    }
  ]
})

export const usePermissionStoreWithOut = () => {
  return usePermissionStore(store)
}
